package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.cart.client.CartInfoFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.user.client.UserInfoFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author 李旭
 * @date 2021/10/20 11:37
 * @Description:
 */
@RestController
@RequestMapping("/api/order")
public class OrderInfoApiController {

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    @Autowired
    private CartInfoFeignClient cartInfoFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoService orderInfoService;
    //去结算页面
    @GetMapping("/trade")
    public Map trade(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        Map result = new HashMap();
//        1、收货地址
        List<UserAddress> userAddressList = userInfoFeignClient.getUserAddressList();
        result.put("userAddressList",userAddressList);//页面对应
//        2、商品清单
        List<CartInfo> cartInfoList = cartInfoFeignClient.getCartInfoListByChecked();
        List<OrderDetail> detailArrayList = cartInfoList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            return orderDetail;
        }).collect(Collectors.toList());//
        result.put("detailArrayList",detailArrayList);//页面对应
//        3、小计  stream
        long sum = detailArrayList.stream().collect(
                Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
        System.out.println("商品的件数：" + sum);
        //总金额   totalPrice =  totalPrice + 单价*数量
        BigDecimal totalPrice = new BigDecimal("0");
        for (OrderDetail orderDetail : detailArrayList) {
            // multiply  乘
            //add  +
            totalPrice = totalPrice.add(orderDetail.getOrderPrice().
                    multiply(new BigDecimal(orderDetail.getSkuNum())));
        }
        result.put("totalNum",sum);//页面对应
        result.put("totalAmount",totalPrice);//页面对应
        //总金额   totalPrice =  totalPrice + 单价*数量
/*        BigDecimal reduce = detailArrayList.stream().map(orderDetail ->
                orderDetail.getOrderPrice().
                        multiply(new BigDecimal(orderDetail.getSkuNum()))
        ).reduce(BigDecimal.ZERO, BigDecimal::add);*/
//        4、订单号、交易号
        //4.1: UUID
        String uuid = UUID.randomUUID().toString();//36位  四个小横线  32
        redisTemplate.opsForValue().set("tradeNo:" + userId ,uuid);
        //4.2: System.currentTimeMillis() + new Random(500); 时间戳
        //4.3:  MD5(userId + skuId)  算法   危险
        result.put("tradeNo",uuid);//页面对应
        //4.4  setnx   setnx 没有  setnx 就有了 已经提交过一次了 不能再提交第二次
        //  什么时候删除呢？
        return result;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,String tradeNo
       ,HttpServletRequest request){//uuid
        String userId = AuthContextHolder.getUserId(request);
        //1:校验交易号是否正确  不正确 重复提交  不要
        if(StringUtils.isEmpty(tradeNo)){
            return Result.fail().message("交易号不能为空");
        }else{
            Object no = redisTemplate.opsForValue().get("tradeNo:" + userId);
            if(StringUtils.isEmpty(no)){
                //缓存中没有
                return Result.fail().message("不要重复提交订单");
            }else{
                if(!tradeNo.equals(no)){
                    return Result.fail().message("交易号不正确");
                }
            }
        }
        //删除交易号
        redisTemplate.delete("tradeNo:" + userId);
        //2:校验库存
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            boolean isHave = orderInfoService.hasStock(orderDetail);
            if(!isHave){
                //库存不足    //2.1:无货  购买数量 > 剩余库存数量
                return Result.fail().message(orderDetail.getSkuName() + "[库存不足]");
            }
        }
        //3:提交订单  （保存订单主表 订单详情表）
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.insertOrder(orderInfo);
        //返回值  给页面使用的订单ID
        return Result.ok(orderId);
    }
    //根据订单ID 查询订单对象
    @GetMapping("/auth/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){

        return orderInfoService.getOrderInfo(orderId);
    }

    //由库存发起的 远程调用订单微服务  要求订单微服务进行 拆单   @ResponseBody
    @PostMapping("/orderSplit")
    public List<Map> orderSplit(Long orderId,String wareSkuMap){

        //wareSkuMap  [{"wareId":"1","skuIds":["2","10"]}    ,{"wareId":"2","skuIds":["3"]}]
        //              wareId 1号仓库ID   skuIds:库存集合     wareId 2号仓库ID  skuIds:库存集合
        //1、开始拆单  1张订单 拆分后 成N多张订单
        List<OrderInfo> subOrderInfoList = orderInfoService.orderSplit(orderId,wareSkuMap);
        //2、返回值 给库存系统
        return subOrderInfoList.stream().map(subOrderInfo -> {
           return orderInfoService.initWareOrder(subOrderInfo);
        }).collect(Collectors.toList());
    }

}
